package org.example.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.Exception.RollBackException;
import org.example.dao.MenuDao;
import org.example.dao.RoleDao;
import org.example.dao.UserDao;
import org.example.domain.PageBean;
import org.example.domain.Role;
import org.example.domain.User;
import org.example.domain.response.ResponseResult;
import org.example.services.RoleService;
import org.example.utils.PageConvertPageBeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.thymeleaf.util.ListUtils;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
@Transactional  //事务回滚
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleDao roleDao;

    @Resource
    private MenuDao menuDao;

    @Resource
    private UserDao userDao;

    @Override
    public ResponseResult getAllRoles() {
        try {
            List<Role> roles = roleDao.selectList(null);
            log.info("获取所有角色信息成功");
            return ResponseResult.success(roles);
        }catch (Exception e){
            e.printStackTrace();
            log.warn("修改所有用户信息失败");
            return ResponseResult.failed("获取全部角色信息失败");
        }
    }

    @Override
    public ResponseResult updateUserRole(int userId, int roleId) {
        try {
            User user = userDao.selectById(userId);
            Role role = roleDao.selectById(roleId);
            if (user == null || role == null){
                log.info("修改用户角色：用户ID或角色ID不存在");
                return ResponseResult.failed("用户ID或角色ID不存在");
            }
            if(role.getRoleKey().equals(userDao.getRoleByUserId(userId))){
                log.info("修改用户角色：{}:{}用户的角色已经是{}，重复修改",user.getUserId(),user.getUsername(),role.getName());
                return ResponseResult.failed("当前用户角色已经修改，请勿再次修改");
            }
            roleDao.updateUserRole(userId,roleId);
            log.info("修改用户角色：修改成功，把{}:{}的角色修改为{}",user.getUserId(),user.getUsername(),role.getName());
            return ResponseResult.success("修改用户角色成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("修改用户角色失败");
            throw new RollBackException("修改用户角色失败");
        }
    }

    @Override
    public ResponseResult updateRoleById(Role role) {
        try {
            Role roleRes = roleDao.selectById(role.getRoleId());
            if(roleRes == null){
                log.info("修改角色信息及权限：角色不存在");
                return ResponseResult.failed("角色不存在，请刷新");
            }
            for (Integer menu : role.getMenuChecked()) {
                if (menuDao.selectById(menu) == null) {
                    return ResponseResult.failed("权限ID中有有错误");
                }
            }
            roleDao.updateById(role);
            menuDao.deleteMenusByRoleId(role.getRoleId());
            menuDao.saveMenusByRoleId(role.getRoleId(),role.getMenuChecked());
            log.info("修改角色信息及权限：成功{}",role);
            return ResponseResult.success("修改角色信息成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("修改角色信息及权限：失败");
            throw new RollBackException("修改角色信息失败");
        }
    }

    @Override
    @PostMapping()
    public ResponseResult saveRole(@RequestBody Role role) {
        try {
            LambdaQueryWrapper<Role> lambdaQueryWrapper = new LambdaQueryWrapper<Role>();
            lambdaQueryWrapper.eq(Role::getRoleKey,role.getRoleKey());
            List<Role> roles = roleDao.selectList(lambdaQueryWrapper);
            if(!ListUtils.isEmpty(roles)){
                log.info("新增角色：该角色已存在");
                return ResponseResult.failed("该角色已存在");
            }
            roleDao.insert(role);
            menuDao.saveMenusByRoleId(role.getRoleId(),role.getMenuChecked());
            log.info("新增角色：新增角色成功");
            return ResponseResult.success("新增角色成功",role);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("新增角色：新增角色失败");
            throw new RollBackException("新增角色失败");
        }
    }

    @Override
    public ResponseResult deleteRole(int roleId) {
        try {
            if(roleId == 1 || roleId == 2 || roleId == 3){
                log.warn("有人尝试删除固定角色");
                return ResponseResult.failed("删除失败，该角色不能删除");
            }
            Role role = roleDao.selectById(roleId);
            if(role == null){
                log.info("删除角色：该角色不存在");
                return ResponseResult.failed("该角色不存在");
            }
            List<Integer> usersIds = roleDao.getUsersByRoleId(roleId);
            if(!ListUtils.isEmpty(usersIds)){
                log.info("删除角色：该角色{}还在使用",usersIds);
                return ResponseResult.failed("角色删除失败，该角色下还有用户存在");
            }
            roleDao.deleteById(roleId);
            log.info("删除角色：删除成功");
            return ResponseResult.success("删除角色成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("删除角色：删除角色失败");
            throw new RollBackException("删除角色失败");
        }
    }

    @Override
    public ResponseResult getRoleByPage(int pageSize, int currentPage) {
        try {
            Page<Role> rolePage = new Page<>(currentPage,pageSize);
            roleDao.selectPage(rolePage,null);
            PageBean<Role> userPageRes = PageConvertPageBeanUtil.convert(rolePage);
            log.info("分页查询角色：成功{}",userPageRes);
            return ResponseResult.success("分页查询角色成功",userPageRes);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("分页查询角色：失败");
            return ResponseResult.failed("分页查询失败");
        }
    }

    @Override
    public ResponseResult getRoleByRoleKey(int pageSize, int currentPage, String roleKey) {
        try {
            Page<Role> rolePage = new Page<>(currentPage,pageSize);
            LambdaQueryWrapper<Role> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.like(Role::getRoleKey,roleKey);
            roleDao.selectPage(rolePage,lambdaQueryWrapper);
            PageBean<Role> userPageRes = PageConvertPageBeanUtil.convert(rolePage);
            log.info("分页查询角色：成功{}",userPageRes);
            return ResponseResult.success("分页查询角色成功",userPageRes);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("分页查询角色：失败");
            return ResponseResult.failed("分页查询失败");
        }
    }
}
